package ua.epam.muzalevskiy.traction.commands;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ua.epam.muzalevskiy.traction.configuretion.MessageConfigurer;
import ua.epam.muzalevskiy.traction.configuretion.PagePathConfigurer;
import ua.epam.muzalevskiy.traction.dao.DaoFactory;
import ua.epam.muzalevskiy.traction.dao.UserDao;
import ua.epam.muzalevskiy.traction.dao.exceptions.NotUniqueParameterException;
import ua.epam.muzalevskiy.traction.user.AuthorizedUser;
import ua.epam.muzalevskiy.traction.user.User;

/**
 * <code>RegisterNewUserCommand</code> class is the <code>Command</code> 
 * interface implementation, that realized <code>Command</code> pattern.
 * Current class encapsulate action of adding new user information to 
 * data base.
 *
 * @author Muzalevskiy Vitaliy
 * @see Command
 * @see User
 * @see RegisteredUser
 */
public class RegisterNewUserCommand implements Command {

    private static DaoFactory factory = new DaoFactory();
    private UserDao userDao = factory.getUserDao();
    private static final String PARAM_NAME_LOGIN = "login";
    private static final String PARAM_NAME_PASSWORD = "password";
    private static final String PARAM_NAME_EMAIL = "email";
    private static final String ATTRIBUTE_NAME_LOGIN = "login";

    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String page = null;
        String login = request.getParameter(PARAM_NAME_LOGIN);
        String pass = request.getParameter(PARAM_NAME_PASSWORD);
        String email = request.getParameter(PARAM_NAME_EMAIL);
        try {
            User user = new AuthorizedUser(login, pass, email);
            userDao.addUser(user);
            page = PagePathConfigurer.getInstance()
                    .getProperty(PagePathConfigurer.NEW_USER_RESULT_PAGE);
            request.setAttribute(ATTRIBUTE_NAME_LOGIN, login);
        } catch (NotUniqueParameterException ex) {
            request.setAttribute(Command.ATTRIBUTE_NAME_ERROR_MESSAGE, 
                    MessageConfigurer.getInstance()
                    .getProperty(MessageConfigurer.REGISTRATION_ERROR_MESSAGE));
            page = PagePathConfigurer.getInstance()
                    .getProperty(PagePathConfigurer.ERROR_PAGE);
        }
        return page;
    }
}
